﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Xml.Serialization;
using DevExpress.XtraEditors;
using ProgramMain.Google;
using ProgramMain.GoogleSearch;

namespace ProgramMain.OpticNet
{
    public partial class SearchMapCtl : ProgramMain.Framework.BaseModalDetailCtl
    {
        public SearchMapCtl()
        {
            InitializeComponent();
        }
        public DialogResult ShowModal()
        {
            m_ShowMode = ShowModeTypes.Edit;
            return ProgramMain.Framework.frmBaseModal.ShowModal(this, "Поиск", null, this.btnCancel);
        }
        private List<SearchResult> _searchResult = new List<SearchResult>();

        private string _serializeAddresses()
        {
            try
            {
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer serializer = new XmlSerializer(typeof (List<SearchResult>));
                serializer.Serialize(memoryStream, _searchResult);
                UTF8Encoding encoding = new UTF8Encoding();
                string vertexXML = encoding.GetString(memoryStream.ToArray());
                return vertexXML;
            }
            catch
            {
                return string.Empty;
            }
        }

        private void _deSerializeAddresses(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return;
            }
            try
            {
                UTF8Encoding encoding = new UTF8Encoding();
                Byte[] byteArray = encoding.GetBytes(data);
                MemoryStream memoryStream = new MemoryStream(byteArray);
                XmlSerializer serializer = new XmlSerializer(typeof (List<SearchResult>));
                _searchResult = new List<SearchResult>((List<SearchResult>) serializer.Deserialize(memoryStream));
                Address.Properties.Items.Clear();
                Address.Properties.Items.AddRange((from q in _searchResult select q.Address).ToArray());
            }
            catch{}
        }

        private void _redirectToMap(SearchResult searchResult)
        {
            IEnumerable<SearchResult> results = from q in _searchResult where q.Address == searchResult.Address select q;
            if (results.Count() ==0)
            {
                _searchResult.Insert(0,searchResult);
                if (_searchResult.Count > 20)
                {
                    _searchResult.RemoveAt(19);
                }

                Address.Properties.Items.Clear();
                Address.Properties.Items.AddRange((from q in _searchResult select q.Address).ToArray());
                string xmlAddesses = _serializeAddresses();
                if (!string.IsNullOrEmpty(xmlAddesses))
                {
                    Properties.Settings.Default.HistorySearchAddress = xmlAddesses;
                    Properties.Settings.Default.Save();
                }
            }
            FrmOpticMap map = FrmOpticMap.ShowForm();
            map.SetCenterMapObject((decimal)searchResult.Coordinate.Longitude, (decimal)searchResult.Coordinate.Latitude);
            map.Level = 18;
            if (this.ParentForm != null)
                this.ParentForm.Close();
           
        }

        private void Redirect()
        {
            if (string.IsNullOrEmpty(Address.Text)) return;
            List<SearchResult> addressList;
            IEnumerable<SearchResult> results = from q in _searchResult where q.Address == Address.Text select q;
            if (results.Count() > 0)
            {
                addressList = results.ToList().GetRange(0, 1);
            }
            else
            {
                GoogleSearch.GoogleSearch search = new GoogleSearch.GoogleSearch(Address.Text);
                addressList = search.Search();
            }

            if (addressList == null) return;
            if (addressList.Count == 1)
            {
                _redirectToMap(addressList[0]);

            }
            else if (addressList.Count == 0)
            {
                XtraMessageBox.Show("Объект не найден", "Сообщение", MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
            }
            if (addressList.Count > 1)
            {
                resultList.DataSource = addressList;
            }
        }

        public override void btnSave_Click(object sender, EventArgs e)
        {
            Redirect();
        }

        private void resultList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (resultList.SelectedItem is SearchResult)
            {
                _redirectToMap((SearchResult)resultList.SelectedItem);
            }
        }

        private void SearchMapCtl_Load(object sender, EventArgs e)
        {
            _deSerializeAddresses(Properties.Settings.Default.HistorySearchAddress);
        }

        private void SearchMapCtl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                Redirect();
        }

        private void Address_QueryPopUp(object sender, CancelEventArgs e)
        {
            Redirect();
        }
    }
}